package com.wiz.web.manager;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.util.Iterator;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.wiz.web.service.ApiService;
import com.wiz.web.service.AuthorityService;
import com.wiz.web.service.BasicService;
import com.wiz.web.service.FuellingService;
import com.wiz.web.service.LoginService;
import com.wiz.web.vo.TransmissionTaskVO;
import com.wiz.web.vo.type.ServiceType;

/**
 * service管理器
 * @author Hakeny
 */
@Service("serviceManager")
public class ServiceManager {
//	private transient final Logger log = LoggerFactory.getLogger(getClass());

	@Resource
	private LoginService loginService;
	@Resource
	private AuthorityService authorityService;
	@Resource
	private FuellingService fuellingService;
	@Resource
	private ApiService apiService;
	
	/**
	 * 各条连接保存 ChannelPipeline 一旦关闭即关闭整个渠道，而不是关闭上下文了
	 */
	private BiMap<String, Channel> stationConnectMap = HashBiMap.create();

	public BiMap<String, Channel> getStationConnectMap() {
		return stationConnectMap;
	}

	/**
	 * 删除值为ctx的整个键值对
	 * @param o
	 */
	public String removeMapByValue(ChannelHandlerContext ctx){
		return this.stationConnectMap.inverse().remove(ctx.channel());
	}
	
	/**
	 * 删除值为ctx的整个键值对
	 * @param o
	 */
	public String getKeyByValue(ChannelHandlerContext ctx){
		return this.stationConnectMap.inverse().get(ctx.channel());
	}
	
	/**
	 * 下发任务队列，站点（1）：任务（N）
	 */
	private Multimap<String, TransmissionTaskVO> transmissionTaskMap = Multimaps.synchronizedMultimap(HashMultimap.<String,TransmissionTaskVO>create());
	
	
	public Multimap<String, TransmissionTaskVO> getTransmissionTaskMap() {
		return transmissionTaskMap;
	}
	
	/**
	 * 删除任务
	 * @param stationId
	 * @param taskIden
	 */
	public void removeTransmissionTask(String stationId,String taskIden){
		Iterator<TransmissionTaskVO> it = transmissionTaskMap.get(stationId).iterator();
		while(it.hasNext()){
			TransmissionTaskVO temp = (TransmissionTaskVO) it.next();
			if(temp.getIdenOnly().equals(taskIden)){
				transmissionTaskMap.remove(stationId, temp);
				break;
			}
		}
	}
	
	/**
	 * 返回相应的service以做业务逻辑
	 * @param servcieType
	 * @return
	 */
	public BasicService getService(int servcieType){
		if(servcieType == ServiceType.LOGIN.getId()){
			return loginService;
		}
		if(servcieType == ServiceType.AUTHORITY.getId()){
			return authorityService;
		}
		if(servcieType == ServiceType.FUELLING.getId()){
			return fuellingService;
		}
		if(servcieType == ServiceType.API.getId()){
			return apiService;
		}
		return null;
	}
}
